package cfca.paperless.client.servlet._1_basic._1_06_CompoundSealAutoPdf;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.io.FileUtils;
import cfca.paperless.client.bean.ChannelBean;
import cfca.paperless.client.bean.MultiDataBean;
import cfca.paperless.client.bean.PdfBean;
import cfca.paperless.client.bean.SealUserInfo;
import cfca.paperless.client.bean.SignLocation;
import cfca.paperless.client.servlet.PaperlessClient;
import cfca.paperless.client.servlet.PaperlessConfig;
import cfca.paperless.client.util.Base64;
import cfca.paperless.client.util.GUID;
import cfca.paperless.client.util.ImageUtil;
import cfca.paperless.client.util.IoUtil;
import cfca.paperless.client.util.PaperlessUtil;
import cfca.paperless.client.util.StrategyUtil;

/**
 * @Description PDF自动化复合签章接口，使用示例。
 * 1，操作对象为本地待处理的单个PDF文件。
 * 2，使用服务端管理页面中预先制作的普通企业印章进行签章。
 * 3，签署1个场景证书印章。
 * 4，签章类型支持4种，1=空白标签签章,2=坐标签章,3=关键字签章，4=位置标识。
 * 5，返回成功签章的PDF文件。
 * 
 * @Author dell
 * @Date 2016-5-13
 * @CodeReviewer TODO
 */
public class CompoundSealAutoPdfTest03 {

    public static void main(String[] args) throws Exception {

        long timeStart = System.currentTimeMillis();// 开始时间

        System.out.println("SealAutoPdfTest01 START");
        
        PaperlessClient clientBean = new PaperlessClient(PaperlessConfig.url, 10000, 60000);
        
        // 如下为用户1手写签名相关的数据，如果没用用户1此处可以省略
        // ************************************************************
        String pngFilePath = "./TestData/handwriting.png";
        
        String pngSuffix = IoUtil.getFileNameSuffix(pngFilePath);
        if(!PaperlessConfig.PNG_FILE_SUFFIX.equals(pngSuffix)){
            throw new Exception("所选文件不是png文件,签章图片文件只支持png格式图片");
        }
        byte[] handwritingImage1 = FileUtils.readFileToByteArray(new File(pngFilePath));
        ImageUtil.resizeImage(handwritingImage1, 20, 20);
        byte[] handwritingData1 = handwritingImage1;
        
        pngFilePath= "./TestData/1.png";
        pngSuffix = IoUtil.getFileNameSuffix(pngFilePath);
        if(!PaperlessConfig.PNG_FILE_SUFFIX.equals(pngSuffix)){
            throw new Exception("所选文件不是png文件,签章图片文件只支持png格式图片");
        }
        byte[] identificationFrontData = FileUtils.readFileToByteArray(new File(pngFilePath));
        
        pngFilePath= "./TestData/2.png";
        pngSuffix = IoUtil.getFileNameSuffix(pngFilePath);
        if(!PaperlessConfig.PNG_FILE_SUFFIX.equals(pngSuffix)){
            throw new Exception("所选文件不是png文件,签章图片文件只支持png格式图片");
        }
        byte[] identificationBackData = FileUtils.readFileToByteArray(new File(pngFilePath));
        
        String filePath = "D:/TestData/wrong.pdf"; //"./TestData/bigFile.pdf";
        
        String pdfSuffix = IoUtil.getFileNameSuffix(filePath);
        if(!PaperlessConfig.PDF_FILE_SUFFIX.equals(pdfSuffix)){
            throw new Exception("所选文件不是pdf文件");
        }
        
        byte[] data11111 = FileUtils.readFileToByteArray(new File(filePath));
        List<MultiDataBean> list1 = new ArrayList<MultiDataBean>();
        list1.add(new MultiDataBean(handwritingData1, "handwritingData.dat", "media-id", "0"));//手写签名数据
        list1.add(new MultiDataBean(handwritingImage1, "handwritingImage.png", "2"));//手写签名图片
        list1.add(new MultiDataBean(identificationFrontData, "identificationFrontImage.png", "2"));//身份证正面
        list1.add(new MultiDataBean(identificationBackData, "identificationBackImage.png", "2"));//身份证反面
        list1.add(new MultiDataBean(data11111, "11111.rar", "2"));
//        list1.add(new MultiDataBean(data11111, "11111.rar", "2"));
//        list1.add(new MultiDataBean(data11111, "11111.rar", "2"));
//        list1.add(new MultiDataBean(data11111, "11111.rar", "2"));
//        list1.add(new MultiDataBean(data11111, "11111.rar", "2"));
        String[] proofHashAndMultiData1 = PaperlessUtil.getProofHashAndMultiData(list1);

        SignLocation signLocation = new SignLocation(1, "人", "R", 10, 0);
        signLocation.setKeywordPositionIndex("2,2,4,9");
        SealUserInfo sealUserInfo = new SealUserInfo("张雨华3", "Z", "113000222000000000", "157446598231", "北京", "签合同");
//        sealUserInfo.setKeyAlg("SM2");
        
        // 设置印章显示大小，可以不设置。比如：100，代表100px。比如需要把章显示为4cm（圆章且DPI为96）时，传入151即可。（并且imageScale配置为0.87）
        //sealUserInfo.setSealImageSize(100);
        
        String proofSealStrategyXml1 = StrategyUtil.createProofSealStrategyXml(handwritingImage1, sealUserInfo, signLocation, proofHashAndMultiData1[0]);
        String sealLayer2Text = "张三";
        String sealLayer2TextStyle = "";//"font-size:12;";
        //String proofSealStrategyXml1 = StrategyUtil.createProofSealStrategyXml(sealLayer2Text,sealLayer2TextStyle, sealUserInfo, signLocation, proofHashAndMultiData1[0]);
        System.out.println(proofSealStrategyXml1);
        // ************************************************************


        String pdfFilePath =  "./TestData/autoCalculatePdfHash.pdf";
        
        pdfSuffix = IoUtil.getFileNameSuffix(pdfFilePath);
        if(!PaperlessConfig.PDF_FILE_SUFFIX.equals(pdfSuffix)){
            throw new Exception("所选文件不是pdf文件");
        }
        
        byte[] pdfFile = FileUtils.readFileToByteArray(new File(pdfFilePath));
        String compoundSealStrategyXml = "<List>" + proofSealStrategyXml1 + "</List>";
        //outputFilePath = "/clsu/pdf/pdf2/" + savedPdfId + ".pdf";
        String multiData = "[" + proofHashAndMultiData1[1] + "]";
        String bizTypeCode = "001";//"001"//业务类型，比如：开户、开通网银
        PdfBean pdfBean = new PdfBean(Base64.toBase64String(pdfFile), bizTypeCode);
        pdfBean.setSavedPdfId("1111111111");
        pdfBean.setPdfOwnerPassword("cfca1234");
        pdfBean.setOutputFilePath("D:/TestData/compoundSealAutopdf01.pdf");
//        pdfBean = new PdfBean("", "a", bizTypeCode, "auto");
//        pdfBean.setInputFilePath("D:\\Tomcat\\SSL\\apache-tomcat-6.0.41\\webapps\\ROOT\\file.pdf");
        //PdfBean pdfBean = new PdfBean(Base64.toBase64String(pdfFile), bizTypeCode);
        String pdfBeanXml = PaperlessUtil.buildPdfBeanXml(pdfBean);
        
        long start = System.currentTimeMillis();
        String channelBeanXml = new ChannelBean(PaperlessConfig.channelCode).toString();

        String systemNo = GUID.generateId();
        
        // 获取场景证书的方式，与证据证书签章策略文件配合使用。默认值为0。0：实时从CFCA CA服务申请下载场景证书；1：使用从CFCA CA服务预先申请下载并存储在本地的场景证书；
        String sceneCertChannel = "0";
        
        // 获取时间戳的方式。默认值为0。0：实时访问CFCA 时间戳服务；1：使用从CFCA购置并在本地部署的时间戳服务器产品；
        String timestampChannel = "0";
        
        
        byte[] sealedPdf = clientBean.compoundSealAutoPdf(systemNo,pdfBeanXml, multiData, compoundSealStrategyXml, PaperlessConfig.operatorCode, channelBeanXml, sceneCertChannel, timestampChannel);

        System.out.println(sealedPdf.length);
        String errorRsString = PaperlessUtil.isError(sealedPdf);
        if ("".equals(errorRsString)) {
            IoUtil.write("./TestData/output/compoundSealAutoPdf.pdf", sealedPdf);
            
        } else {
            System.out.println(new String(sealedPdf, "UTF-8"));
        }
        System.out.println("########## compoundSealAutoPdf" + " end,time:" + (System.currentTimeMillis() - start) + "##########");
    }

}
